package com.peng.ognltest;

import java.util.HashMap;
import java.util.Map;

import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ognl.Ognl;
import ognl.OgnlException;

/**
 * OgnlDemo
 *
 * @author lupeng
 * Created on 2022-03-22
 */
public class OgnlDemo {

    private static final Logger logger = LoggerFactory.getLogger(OgnlDemo.class);

    @Test
    public void demo1() throws OgnlException {
        User user = new User("com/peng/test", 23);
        Address address = new Address("330108", "杭州市滨江区");
        user.setAddress(address);

        System.out.println(Ognl.getValue("name", user));
        System.out.println(Ognl.getValue("name.length", user));
        System.out.println(Ognl.getValue("address", user));
        System.out.println(Ognl.getValue("address.port", user));
    }

    /**
     * 静态方法调用
     */
    @Test
    public void demo2() throws OgnlException {
        System.out.println(Ognl.getValue("@java.lang.Math@max(1, 100)", null));
        System.out.println(Ognl.getValue("@java.lang.Integer@MIN_VALUE", null));
    }


    @Test
    public void demo3() throws OgnlException {
        Map<String, Object> context = new HashMap<>();
        User user = new User("com/peng/test", 23);
        Address address = new Address("330108", "杭州市滨江区");
        user.setAddress(address);

        context.put("val1", "12345678");
        context.put("user", user);

        Object value = Ognl.getValue(Ognl.parseExpression("user.name"), context);
        Object value1 = Ognl.getValue(Ognl.parseExpression("#user.name=#val1"), context, user);
        System.out.println(Ognl.getValue(Ognl.parseExpression("user.name"), context));

    }
}
